package com.shipwe.loans.ui.presenter

import com.shipwe.loans.configs.ShipweConfigs
import com.shipwe.loans.http.ApiService
import com.shipwe.loans.http.ApiService.addCommonParams
import com.shipwe.loans.http.IHttpCallback
import com.shipwe.loans.pro.ShipwePresenter
import com.shipwe.loans.ui.view.IHomeView
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.helper.CustomProcessHelper
import com.shipwe.loans.utils.helper.ProductStatusHelper
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import com.shipwe.permission.OnPermissionCallback
import com.shipwe.permission.XXPermissions
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/18 11:59
 * @Annotation：主页 Presenter 实现
 */
class HomePresenter(private val iView: IHomeView): ShipwePresenter(iView), CoroutineScope by MainScope() {

    private val TYPE_PRODUCT = "TYPE_PRODUCT"//产品
    private val TYPE_PRODUCT_APPLIED = "TYPE_PRODUCT_APPLIED"//已申请产品
    private val TYPE_NO_MORE = "TYPE_NO_MORE"//No more
    private val TYPE_APPLIED_EMPTY = "TYPE_APPLIED_EMPTY"//applied Empty
    private val TYPE_PRODUCT_EMPTY = "TYPE_PRODUCT_EMPTY"//product Empty

    //当前产品类型 1:products  2:applied
    private var curtType = 1
    //所有权限
    private var allPermissions: ArrayList<String>? = null
    //选择的产品
    private var selectProduct: JSONObject? = null

    /**
     * 获取所有权限列表
     */
    fun loadHomeAllPermissionsAction() {
        if (allPermissions == null){
            allPermissions = arrayListOf()
        }
        allPermissions?.clear()
        launch {
            val customize = CustomConfigsHelper.getShipweConfigData()
            if(customize != null){
                val permissions = customize.optJSONObject("permissions")
                if (permissions != null){
                    val permission = permissions.optJSONArray("permission")
                    if (permission != null && permission.length() > 0){
                        for (i in 0..<permission.length()){
                            allPermissions!!.add(permission.optString(i))
                        }
                    }

                    val home = permissions.optJSONArray("home")
                    if (home != null && home.length() > 0){
                        for (i in 0..<home.length()){
                            val str = home.optString(i)
                            if (allPermissions!!.contains(str)){
                                continue
                            }
                            allPermissions!!.add(str)
                        }
                    }
                }
            }
        }
    }

    /**
     * 切换产品列表
     * pType  1  可申请、不可申请
     *       2  审核中、放款中、已拒绝
     */
    fun checkHomeProductType(pType: Int){
        curtType = pType
        when(pType){
            1 -> {
                iView.showHomeProductView()
            }
            else -> {
                iView.showHomeAppliedView()
            }
        }
        loadHomeProductListAction()
    }

    /**
     * 加载产品表
     */
    fun loadHomeProductListAction(){
        val pList = ArrayList<JSONObject>()
        //产品数据源
        val pData = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_PRODUCT)
        when(curtType){
            1 -> {
                //待申请的产品列表
                val list = getHomeAvailableProductList(pData)
                if (list != null){
                    pList.addAll(list)
                }
            }
            else -> {
                //已申请产品列表
                val appliedList = getHomeAppliedProductList(pData)
                if (appliedList != null){
                    pList.addAll(appliedList)
                }
            }
        }

        if (pList.size > 0){
            pList.add(getHomeProductNoMoreItem())
        } else {
            pList.add(getHomeProductEmptyItem())
        }
        iView.showHomeProductList(pList)
    }

    /**
     * 可申请 && 不可申请 列表
     */
    private fun getHomeAvailableProductList(pData: String): ArrayList<JSONObject>?{
        if (pData.isNotEmpty()){
            val pList = arrayListOf<JSONObject>()
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                item.put("itemType",TYPE_PRODUCT)
                val status = item.optString("status")
                val applyStatus = item.optString("applyStatus")
                val activeFlag = item.optString("activeFlag")

                //已拒绝
                if (ProductStatusHelper.StatusRepository(applyStatus).isRejected()){
                    continue
                }

                if (status == "APPLY"){//待申请状态
                    pList.add(item)
                }
            }
            return pList
        }
        return null
    }

    /**
     * 产品列表
     */
    private fun getHomeAppliedProductList(pData: String): ArrayList<JSONObject>?{
        if (pData.isNotEmpty()){
            val pList = arrayListOf<JSONObject>()
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                item.put("itemType",TYPE_PRODUCT_APPLIED)
                val status = item.optString("status")
                val applyStatus = item.optString("applyStatus")
                val activeFlag = item.optString("activeFlag")

                //已拒绝
                if (ProductStatusHelper.StatusRepository(applyStatus).isRejected()){
                    pList.add(item)
                    continue
                }
                //非可申请 && 非待还款
                if (activeFlag == "YES" && status != "APPLY" && status != "REPAYMENT"){
                    pList.add(item)
                }
            }
            return pList
        }
        return null
    }

    /**
     * 没有更多数据
     */
    private fun getHomeProductNoMoreItem(): JSONObject{
        return JSONObject().put("itemType",TYPE_NO_MORE)
    }

    /**
     * 没有数据
     */
    private fun getHomeProductEmptyItem(): JSONObject{
        return when(curtType){
            1 -> {//可申请
                JSONObject().put("itemType",TYPE_PRODUCT_EMPTY)
            }
            else -> {//已申请
                JSONObject().put("itemType",TYPE_APPLIED_EMPTY)
            }
        }
    }


    /**
     * 设置申贷的产品
     */
    fun setHomeSelectProduct(product: JSONObject){
        this.selectProduct = product
    }

    /**
     * 复制主产品信息到目标产品
     */
    private fun onHomeCopyProductToChildProductAction(targetProduct: String){
        iView.showShipweLoading()
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path",ApiService.API_PATH.SHIPWE_API_LOAN_PRODUCT_COPY_PATH)
                put("sourceProduct", ShipweConfigs.SHIPWE_APPNAME)
                put("targetProduct", targetProduct)
            }
        val httpUrl = ApiService.getHttpUrl()
        doHttpPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                var pToken = ""
                if (obj != null){
                    pToken = obj.optString("token","")
                }
                if (pToken.isEmpty()){
                    pToken = selectProduct!!.optString("token")
                }
                val pName = selectProduct!!.optString("product")
                iView.showHomeLoanApplyPage(pName,pToken)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                iView.dismissShipweLoading()
            }
        })
    }

    /**
     * 检查权限是否全部申请
     */
    fun checkHomeAllPermissionsAgree(){
        if (XXPermissions.isGranted(iView.getAct(),allPermissions!!)){
            iView.showHomeCheckPermissionSuccess()
            return
        }

        //是否是审核账号
        val isConfigAccount = ShipweSharedHelper.getShipweSharedBoolean(ShipweSharedKey.SHIPWE_IS_CONFIG_ACCOUNT)
        if(isConfigAccount) {//审核账号，可以进行申贷操作
            iView.showHomeCheckPermissionSuccess()
            return
        }

        XXPermissions.with(iView.getAct())
            // 申请多个权限
            .permission(allPermissions!!)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        iView.showHomeCheckPermissionSuccess()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    XXPermissions.startPermissionActivity(iView.getAct(),permissions)
                }
            })
    }

    /**
     * 验证认证流程是否完成
     */
    fun checkHomeAllStepsAction(){
        if (CustomProcessHelper.getAuthStepList().size == 0){//流程已完成 - 进入申贷确认页
            val pName = selectProduct!!.optString("product")
            val pToken = selectProduct!!.optString("token")
            //非主产品
            if (pName != ShipweConfigs.SHIPWE_APPNAME){
                //copy 主产品信息到子产品
                onHomeCopyProductToChildProductAction(pName)
            } else {
                //主产品进入申待确认页
                iView.showHomeLoanApplyPage(pName,pToken)
            }
        } else {//流程未完成 - 进入 认证步骤页面
            iView.showHomeProcessStepsPage()
        }
    }
}